import os.path
import smtplib
import time
from email.message import Message
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from loguru import logger


def create_attachment(filepath: str) -> Message:
    """创建附件

    :param filepath: 附件
    :return:
    :rtype: Message
    """
    filepath = os.fspath(filepath)
    if not os.path.exists(filepath):
        raise FileNotFoundError(f'{filepath} is not exists!')
    filename = os.path.basename(filepath)
    attachment = MIMEApplication(open(filepath, 'rb').read())
    attachment.add_header('content-disposition', 'attachment', filename=filename)
    return attachment


def create_mail(from_addr: str, to_addrs: list, filepath: str) -> Message:
    """创建邮件

    :param from_addr: 寄件人
    :param to_addrs: 收件人列表用于群发
    :param filepath: 附件
    :return:
    :rtype: Message
    """
    # 创建复合邮件对象
    msg = MIMEMultipart()

    # 填写寄件人、收件人和主题
    msg['From'] = from_addr
    msg['To'] = ', '.join(to_addrs)
    msg['Subject'] = '自动化测试报告'

    # 构造正文内容
    content = """
您好：
    数据资源平台DataQ {} 的自动化测试报告详情请查收附件。
    如有问题请及时联系我，多谢！
    """.format(time.strftime('%Y-%m-%d %H:%M:%S'))
    # 创建正文邮件对象并添加到复合邮件对象
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    # 创建附件邮件对象并添加到复合邮件对象
    msg.attach(create_attachment(filepath))

    return msg


def send_mail(username: str, password: str, to_addrs: list, msg: Message) -> None:
    """发送邮件

    :param username: 邮箱账号
    :param password: 邮箱密码/授权码
    :param to_addrs: 收件人列表用于群发
    :param msg: 邮件内容
    :return:
    :rtype:
    """
    smtp = smtplib.SMTP()
    try:
        smtp = smtplib.SMTP_SSL('smtp.isoftstone.com', 465)
        smtp.login(username, password)
        smtp.set_debuglevel(1)
        smtp.sendmail(username, to_addrs, msg.as_string())
    except smtplib.SMTPException as e:
        logger.error(f'send email failed!, {e}')
    else:
        logger.info('send email success!')
    finally:
        smtp.quit()


def main():
    """程序入口

    :return:
    """
    username = 'xsweid@isoftstone.com'
    password = '软通ipsa账号对应的密码'
    receivers = ['xsweid@isoftstone.com', 'yjluok@isoftstone.com']
    msg = create_mail(username, receivers, '2022-08-15_15-49-30.html')
    send_mail(username, password, receivers, msg)


if __name__ == '__main__':
    main()
